/*
 * @Author: xiaosihan
 * @Date: 2023-04-18 15:18:19
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-08-29 16:38:21
 */

import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { get } from "lodash";
import { message } from "antd";
import utils from "../utils/utils";

// 前端请求的基类
export default class Api {
  constructor() {}

  //访问域名
  baseURL = `//api.open3dcloud.com/${utils.isProd ? "klbg" : "test/klbg"}`;

  //开发模式访问的域名
  devBaseURL = "/api";

  //超时时间
  timeout = 60000;

  // 带凭据
  withCredentials = false;

  // 创建 请求实例
  _createInstance() {
    const headers = {};
    if (localStorage.token) {
      Object.assign(headers, {
        Authorization: `Bearer ${localStorage.token}`,
      });
    }

    const axiosInstance = axios.create({
      baseURL: utils.isDev ? this.devBaseURL : this.baseURL,
      timeout: this.timeout,
      headers: headers,
      // withCredentials: true
    });

    // 响应拦截器
    axiosInstance.interceptors.response.use((res: AxiosResponse) => {
      return this._responseInterceptors(res);
    });

    return axiosInstance;
  }

  // 请求拦截器
  _requestInterceptors(config: AxiosRequestConfig): AxiosRequestConfig {
    return config;
  }

  // 响应拦截器
  _responseInterceptors(res: AxiosResponse): AxiosResponse {
    if (!get(res, ["data", "success"])) {
      const msg = get(res, ["data", "message"]);
      console.error(msg);
      message.error(msg);
    }
    return res.data;
  }

  // get请求
  _get(url: string, params?: {}) {
    const headers = {
      "Content-Type": "application/x-www-form-urlencoded",
    };
    if (localStorage.token) {
      Object.assign(headers, {
        Authorization: `Bearer ${localStorage.token}`,
      });
    }

    return this._createInstance().get(url, {
      params,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
  }

  // post 请求
  _post(url: string, data = {}) {
    return this._createInstance().post(url, data);
  }

  // 上传
  _upload(url: string, file: any) {
    return axios
      .create({
        baseURL: utils.isDev ? this.devBaseURL : this.baseURL,
        timeout: this.timeout,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        withCredentials: this.withCredentials,
      })
      .post(url, file);
  }
}
